package org.carry.god.framework.mp.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.carry.god.framework.mp.pojo.BaseDO;
import org.carry.god.framework.satoken.utils.SaTokenFrameworkUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author wanglei
 */
public class BaseFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject != null && metaObject.getOriginalObject() instanceof BaseDO baseDO) {
            LocalDateTime current = LocalDateTime.now();
            // 创建时间为空，则以当前时间为插入时间
            if (Objects.isNull(baseDO.getCreateTime())) {
                baseDO.setCreateTime(current);
            }
            Long userId = SaTokenFrameworkUtils.getLoginUserId();
            // 当前登录用户不为空，创建人为空，则当前登录用户为创建人
            if (userId != null && Objects.isNull(baseDO.getCreateBy())) {
                baseDO.setCreateBy(userId);
            }

            updateInfo(baseDO, current, userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject != null && metaObject.getOriginalObject() instanceof BaseDO baseDO) {
            LocalDateTime current = LocalDateTime.now();
            Long userId = SaTokenFrameworkUtils.getLoginUserId();
            updateInfo(baseDO, current, userId);
        }
    }

    /**
     * 更新信息
     * @param baseDO 基础信息
     * @param current 当前时间
     * @param userId 当前登录用户ID
     */
    private static void updateInfo(BaseDO baseDO, LocalDateTime current, Long userId) {
        // 更新时间为空，则以当前时间为更新时间
        if (Objects.isNull(baseDO.getUpdateTime())) {
            baseDO.setUpdateTime(current);
        }

        // 当前登录用户不为空，更新人为空，则当前登录用户为更新人
        if (userId != null && Objects.isNull(baseDO.getUpdateBy())) {
            baseDO.setUpdateBy(userId);
        }
    }
}
